<template>
  <el-card class="box-card">
    <el-form
      :model="spuInfo"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <!-- spu品牌下拉列表 -->
      <el-form-item label="spu品牌" prop="tmId">
        <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
          <el-option
            :label="item.name"
            :value="item.id"
            v-for="(item, index) in attrList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- SPU描述 -->
      <el-form-item label="SPU描述" prop="description">
        <el-input type="textarea" v-model="spuInfo.description"></el-input>
      </el-form-item>
      <!-- 上传图片墙 -->
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          :action="`${baseAPI}/admin/product/fileUpload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <i class="el-icon-plus"></i>
          <div slot="tip" style="font-size: 12px">只能上传500kb图片</div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" width="30%">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <!-- 销售属性 -->
      <el-form-item label="销售属性">
        <el-select placeholder="请选择销售属性" v-model="spuSale">
          <el-option
            :label="list.name"
            :value="list.id"
            v-for="list in saleList"
            :key="list.id"
          ></el-option>
        </el-select>
        <el-button
          icon="el-icon-plus"
          type="primary"
          :disabled="!spuSale"
          @click="addSaleList"
        >
          添加属性
        </el-button>
      </el-form-item>
      <!-- 表格 -->
      <el-form-item prop="spuSaleAttrList">
        <el-table :data="spuInfo.spuSaleAttrList" border style="width: 100%">
          <el-table-column
            prop="index"
            label="序号"
            width="50"
            type="index"
          ></el-table-column>
          <el-table-column
            label="属性名"
            width="280"
            prop="saleAttrName"
          ></el-table-column>
          <el-table-column label="属性值列表" prop="spuSaleAttrValueList">
            <template v-slot="{ row, $index }">
              <el-tag
                v-for="item in row.spuSaleAttrValueList"
                :key="item.saleAttrValueName"
              >
                {{ item.saleAttrValueName }}
              </el-tag>
              <!-- 添加标签 -->
              <el-input
                v-show="row.isEdit"
                class="input-new-tag"
                :ref="$index"
                size="small"
                v-model="inputValue"
                @blur="handleInputConfirm(row)"
              ></el-input>
              <el-button
                class="button-new-tag"
                size="small"
                v-show="!row.isEdit"
                @click="addSaleAttrList(row, $index)"
              >
                + 添加属性
              </el-button>
            </template>
          </el-table-column>
          <!-- 删除按钮 -->
          <el-table-column label="操作" width="150">
            <template v-slot="{ row }">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="delSale(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <!-- 确认按钮 -->
      <el-form-item>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
        <el-button @click="$emit('update:visible', 0)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getAttrList, baseSaleList, setSaleList } from '@/api/spu'
import { mapState } from 'vuex'

export default {
  name: 'AddSpu',
  data() {
    //自定义校验
    var checkAge = (rule, value, callback) => {
      if (!this.spuInfo.spuSaleAttrList.length) {
        return callback(new Error('最少添加一个属性'))
      }
      this.spuInfo.spuSaleAttrList.forEach(item => {
        if (!item.spuSaleAttrValueList.length) {
          return callback(new Error('属性最少要有一个属性值'))
        }
      })
      //必须添加
      callback()
    }
    return {
      inputValue: '',
      baseAPI: process.env.VUE_APP_BASE_API,
      saleList: [], //销售属性列表
      attrList: [], //商标列表
      spuSale: '', //销售属性值
      spuInfo: {
        spuName: '', // 名称
        tmId: '', // 品牌id
        description: '', // 描述
        spuImageList: [], // 图片列表
        spuSaleAttrList: [] // 列表属性
      },
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        spuName: [
          { required: true, message: '请输入spu名称名称', trigger: 'blur' }
        ],
        tmId: [
          { required: true, message: '请选择品牌名称', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请填写描述', trigger: 'blur' }
        ],
        spuImageList: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        spuSaleAttrList: [{ validator: checkAge, trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapState('cartgory', ['cartGory3Id'])
  },
  async mounted() {
    let res = await getAttrList()
    let resTwo = await baseSaleList()
    this.saleList = resTwo
    this.attrList = res.map(item => {
      return {
        name: item.tmName,
        id: item.id
      }
    })
  },
  methods: {
    //删除图片触发
    handleRemove(file, fileList) {
      console.log(file, fileList)
      // let imgName fileList.name
      //let imgUrl = fileList.response.data
      this.spuInfo.spuImageList = fileList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.response.data
        }
      })
    },
    //放大
    handlePictureCardPreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //上传成功触发的回调
    handleAvatarSuccess(res, file) {
      let imgName = file.name
      let imgUrl = res.data
      this.spuInfo.spuImageList.push({ imgName, imgUrl })
    },
    // 上传之前触发的回调
    beforeAvatarUpload(file) {
      // file 上传的图片文件信息
      // file.type 文件类型
      const validFileType = ['image/jpeg', 'image/jpg', 'image/png']
      const isValidFileType = validFileType.indexOf(file.type) > -1
      // file.size 文件大小
      const isLt = file.size / 1024 < 500

      if (!isValidFileType) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt) {
        this.$message.error('上传头像图片大小不能超过 500KB!')
      }
      // 返回值 true 可以上传
      // 返回值 false 不会上传
      return isValidFileType && isLt
    },
    //添加销售属性
    addSaleList() {
      //一个id 一个name
      // console.log(this.saleList);
      let text = ''
      this.saleList = this.saleList.filter(item => {
        if (item.id === this.spuSale) {
          text = item.name
        }
        return item.id !== this.spuSale
      })

      this.spuInfo.spuSaleAttrList.push({
        saleAttrName: text,
        baseSaleAttrId: this.spuSale,
        isEdit: true,
        spuSaleAttrValueList: []
      })
      this.$nextTick(() => {
        this.$refs[this.spuInfo.spuSaleAttrList.length - 1].focus()
      })
      this.spuSale = ''
    },
    //删除销售属性
    delSale(row) {
      // console.log(row.saleAttrName, row.id);
      let { saleAttrName, id } = row
      this.spuInfo.spuSaleAttrList = this.spuInfo.spuSaleAttrList.filter(
        item => {
          return item.saleAttrName !== saleAttrName
        }
      )
      this.saleList.push({ name: saleAttrName, id })
      this.saleList.sort((a, b) => {
        return a.id - b.id
      })
    },

    //失焦和回车出发
    handleInputConfirm(row) {
      let inputValue = this.inputValue

      let show = row.spuSaleAttrValueList.some((item, index) => {
        return item.saleAttrValueName === inputValue
      })
      if (show) {
        this.$message({
          message: '添加的属性不能重复',
          type: 'warning'
        })
        return
      }
      if (inputValue) {
        row.spuSaleAttrValueList.push({
          baseSaleAttrId: row.baseSaleAttrId,
          saleAttrValueName: inputValue,
          saleAttrName: row.saleAttrName
        })
      }
      
      row.isEdit = false
      this.inputValue = ''
    },

    //点击显示input 聚焦
    addSaleAttrList(row, index) {
      row.isEdit = true
      // console.log(row);
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },

    //确认添加
    confirmAdd() {
      let {
        spuImageList,
        description,
        spuName,
        spuSaleAttrList,
        tmId
      } = this.spuInfo
      let { cartGory3Id } = this
      let data = {
        category3Id: cartGory3Id, //三级菜单
        description, //描述
        spuImageList,
        spuName, //名称
        spuSaleAttrList,
        tmId
      }
      console.log(data)
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          await setSaleList(data)
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.$emit('update:visible', 0)
        } else {
          console.log('校验不通过')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
